from PIL import Image


def make_background_transparent(img_path, output_path):
    # 打开图片并转换为RGBA模式
    image = Image.open(img_path).convert("RGBA")
    datas = image.getdata()

    # 定义要替换为透明的灰度值集合
    target_grays = {246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236,235,234,233,232,231,230,255}

    new_data = []
    for item in datas:
        r, g, b, a = item
        # 检查是否为灰度色且值在目标集合中
        if r == g == b and r in target_grays:
            new_data.append((r, g, b, 0))  # 设置为完全透明
        else:
            new_data.append(item)

    image.putdata(new_data)
    image.save(output_path, "PNG")


# 使用示例
make_background_transparent('output_image1.png', 'output_image.png')